﻿namespace HZY.Api.Admin.Controllers.Systems;

/// <summary>
/// 组织机构控制器
/// </summary>
[ControllerDescriptor(MenuId = "21", DisplayName = "组织机构")]
public class SysOrganizationController(
    IServiceProvider serviceProvider,
    IRepository<SysOrganization> sysOrganizationRepository,
    IAccountService accountService)
    : AdminControllerBase<SysOrganizationService>(serviceProvider)
{
    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="search"></param>
    /// <returns></returns>
    [ActionDescriptor(DisplayName = "查看列表")]
    [HttpPost]
    public async Task<List<SysOrganization>> FindListAsync([FromBody] SysOrganization search)
    {
        return await Service.FindListAsync(search);
    }

    /// <summary>
    /// 查询表单数据
    /// </summary>
    /// <param name="id"></param>
    /// <param name="parentId"></param>
    /// <returns></returns>
    [ActionDescriptor(DisplayName = "查看表单")]
    [HttpGet("{id?}/{parentId?}")]
    public async Task<Dictionary<string, object?>> FindFormAsync([FromRoute] int id, int parentId)
    {
        return await Service.FindFormAsync(id, parentId);
    }

    /// <summary>
    /// 获取组织架构树
    /// </summary>
    /// <returns></returns>
    [ActionDescriptor(DisplayName = "查看组织架构树")]
    [HttpPost]
    [Time("查看组织架构树")]
    public async Task<dynamic> GetSysOrganizationTreeAsync()
    {
        var expandedRowKeys = new List<int>();

        var accountInfo = accountService.GetAccountContext();

        var sysOrganizationAll = await sysOrganizationRepository
            .DataPermission(sysOrganizationRepository.SelectNoTracking, accountInfo, s => s.CreatorUserId!, s => s.Id)
            .OrderBy(w => w.OrderNumber)
            .ToListAsync();

        return new
        {
            expandedRowKeys,
            allKeys = sysOrganizationAll.OrderBy(w => w.OrderNumber).Select(w => w.Id).ToList(),
            rows = sysOrganizationAll
        };
    }
}